package com.example.xposedtest.network;

import android.util.Log;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * DeepSeek AI API 客户端（仅负责网络请求和响应解析）
 */
public class DeepSeekApiClient {
    private static final String TAG = "DeepSeek-Api";
    private static final String API_URL = "https://api.deepseek.com/v1/chat/completions";
    private static final String API_KEY = "sk-8a29e78fc03541eea33835e6e7dfdf4c"; // 替换为你的API密钥
    private static final int TIMEOUT = 10000; // 10秒超时

    /**
     * 发送用户消息到DeepSeek，获取AI回复
     * @param userMessage 用户输入的消息
     * @return AI回复文本（失败返回友好提示）
     */
    public String getReply(String userMessage) {
        try {
            // 1. 创建URL连接
            URL url = new URL(API_URL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Authorization", "Bearer " + API_KEY);
            conn.setDoOutput(true);
            conn.setConnectTimeout(TIMEOUT);
            conn.setReadTimeout(TIMEOUT);

            // 2. 构建请求体（JSON格式）
            String requestBody = buildRequestBody(userMessage);

            // 3. 发送请求
            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = requestBody.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // 4. 处理响应
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取成功响应
                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = in.readLine()) != null) {
                    response.append(line);
                }
                in.close();
                return parseResponse(response.toString()); // 解析AI回复
            } else {
                // 读取错误响应
                Log.e(TAG, "API请求失败，响应码：" + responseCode);
                BufferedReader errorIn = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
                StringBuilder errorResponse = new StringBuilder();
                String line;
                while ((line = errorIn.readLine()) != null) {
                    errorResponse.append(line);
                }
                errorIn.close();
                Log.e(TAG, "错误详情：" + errorResponse.toString());
                return "抱歉，AI回复请求失败";
            }
        } catch (Exception e) {
            Log.e(TAG, "API调用异常", e);
            return "抱歉，处理消息时出现网络问题";
        }
    }

    /**
     * 构建API请求体（符合DeepSeek接口规范）
     */
    private String buildRequestBody(String userMessage) {
        try {
            JSONObject request = new JSONObject();
            request.put("model", "deepseek-chat"); // 模型名称
            request.put("temperature", 0.7); // 随机性（0-1）
            request.put("max_tokens", 2000); // 最大回复长度

            // 消息列表（系统提示 + 用户消息）
            JSONArray messages = new JSONArray();
            // 系统提示（定义AI角色）
            JSONObject systemMsg = new JSONObject();
            systemMsg.put("role", "system");
            systemMsg.put("content", "你是一个友好的微信自动回复助手，回复简洁、自然，符合日常聊天语境。");
            messages.put(systemMsg);

            // 用户消息
            JSONObject userMsg = new JSONObject();
            userMsg.put("role", "user");
            userMsg.put("content", userMessage);
            messages.put(userMsg);

            request.put("messages", messages);
            return request.toString();
        } catch (Exception e) {
            Log.e(TAG, "构建请求体失败", e);
            return "{}"; // 异常时返回空JSON
        }
    }

    /**
     * 解析API响应（提取AI回复内容）
     */
    private String parseResponse(String response) {
        try {
            JSONObject json = new JSONObject(response);
            JSONArray choices = json.getJSONArray("choices");
            if (choices.length() > 0) {
                JSONObject choice = choices.getJSONObject(0);
                JSONObject message = choice.getJSONObject("message");
                return message.getString("content").trim();
            }
            return "抱歉，未获取到AI回复";
        } catch (Exception e) {
            Log.e(TAG, "解析响应失败", e);
            return "抱歉，解析AI回复时出错";
        }
    }
}